package com.liuyc.lib.tools.browser

import android.app.Activity
import android.content.Context
import android.text.Selection
import android.text.Spannable
import android.view.inputmethod.InputMethodManager
import android.widget.EditText

object KeyboardUtils {

    /**
     * 隐藏输入盘
     *
     * @param activity
     */
    fun collapseSoftInput(activity: Activity) {
        val inputMethodManager: InputMethodManager = activity
            .getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        if (inputMethodManager.isActive()) {
            if (activity.getCurrentFocus() != null) {
                inputMethodManager.hideSoftInputFromWindow(
                    activity.getCurrentFocus()!!.getWindowToken(),
                    InputMethodManager.HIDE_NOT_ALWAYS
                )
            }
        }
    }

    /**
     * 显示输入盘
     *
     * @param context
     * @param inputText
     */
    fun showSoftInput(context: Context, inputText: EditText) {
        val imm = context
            .getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.showSoftInput(inputText, InputMethodManager.RESULT_SHOWN)
        imm.toggleSoftInput(
            InputMethodManager.SHOW_FORCED,
            InputMethodManager.HIDE_IMPLICIT_ONLY
        )
    }

    /**
     * 隐藏输入盘
     *
     * @param context
     * @param inputText
     */
    fun hideSoftInput(context: Context, inputText: EditText) {
        val imm = context
            .getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(inputText.windowToken, 0)
    }

    /**
     * 设置EditText的光标
     *
     * @param editText
     */
    fun setFocus(editText: EditText) {
        editText.requestFocus()
        val text: CharSequence = editText.text
        if (text is Spannable) {
            Selection.setSelection(text as Spannable, text.length)
        }
    }

    /**
     * 设置EditText的光标并选择文字
     *
     * @param editText
     */
    fun setFocusAndSelection(editText: EditText) {
        editText.requestFocus();

        var text = editText.getText();
        if (text is Spannable) {
            Selection.selectAll(text as Spannable);
        }
    }

}